package com.mall.common.db.mybatisplus;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * 通用填充类 适用于mybatis plus
 */
public class CommonMetaObjectHandler implements MetaObjectHandler {

    /**
     * 创建时间
     */
    private final String createTime = "createTime";
    /**
     * 修改时间
     */
    private final String updateTime = "updateTime";

    /**
     * 创建日期
     */
    private final String createDate = "createDate";
    /**
     * 修改日期
     */
    private final String updateDate = "updateDate";

    @Override
    public void insertFill(MetaObject metaObject) {
        //有主动设值则不进行填充处理 null为不处理
        setInsertFieldValByName(createTime, metaObject.hasSetter(createTime) && Objects.nonNull(metaObject.getValue(createTime)) ? null : LocalDateTime.now(), metaObject);
        setInsertFieldValByName(createDate, metaObject.hasSetter(createDate) && Objects.nonNull(metaObject.getValue(createDate)) ? null : LocalDate.now(), metaObject);
        setInsertFieldValByName(updateTime, metaObject.hasSetter(updateTime) && Objects.nonNull(metaObject.getValue(updateTime)) ? null : LocalDateTime.now(), metaObject);
        setInsertFieldValByName(updateDate, metaObject.hasSetter(updateDate) && Objects.nonNull(metaObject.getValue(updateDate)) ? null : LocalDate.now(), metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        setUpdateFieldValByName(updateTime, LocalDateTime.now(), metaObject);
        setUpdateFieldValByName(updateDate, LocalDate.now(), metaObject);
    }

}
